package Command

import "fmt"

/**
- [行为型_命令模式](http://c.biancheng.net/view/1380.html)
- 三要素：命令发送方 → 命令 → 命令接收方
*/

type Person struct {
	name string  // 命令发送方
	cmd  Command // 发送命令(命令接收者+接收者执行的命令)
}
type Command struct {
	person *Person
	method func()
}

func NewCommand(p *Person, method func()) Command {
	return Command{
		person: p,
		method: method,
	}
}

func (c *Command) Excete() {
	c.method()
}

func NewPerson(name string, cmd Command) Person {
	return Person{
		name: name,
		cmd:  cmd,
	}
}

func (p *Person) Buy() {
	fmt.Println(fmt.Sprintf("%s is buying", p.name))
	p.cmd.Excete()
}

func (p *Person) Cook() {
	fmt.Println(fmt.Sprintf("%s is cooking", p.name))
	p.cmd.Excete()
}
func (p *Person) Wash() {
	fmt.Println(fmt.Sprintf("%s is washing ", p.name))
	p.cmd.Excete()
}

// 因为测试函数添加该command前，commond是nil，所以不执行p.cmd.Excete()
func (p *Person) Listen() {
	fmt.Println(fmt.Sprintf("%s is Listening...", p.name))
}

func (p *Person) Talk() {
	fmt.Println(fmt.Sprintf("%s is Talking ", p.name))
	p.cmd.Excete()
}
